package com.easykoo.ioc.xml;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;

public class XMLParser {
	private static Log logger = LogFactory.getLog(XMLParser.class);

	public static Map<String, Object> parse(Document doc) {
		Map<String, Object> beanMap = new HashMap<String, Object>();
		@SuppressWarnings("unchecked")
		List<Element> beansList = doc.selectNodes("//bean");
		for (Element element : (Iterable<Element>) beansList) {

			Entry bean = new Entry();
			String id = element.attribute("id").getValue();
			bean.setId(id);
			String clazz = element.attribute("class").getValue();
			bean.setClazz(clazz);
			Attribute autowireAtb = element.attribute("autowire");
			String autowire = null;
			if (autowireAtb != null) {
				autowire = autowireAtb.getValue();
				bean.setAutowire(autowire);
			}
			if (autowire == null || !"byName".equals(autowire)) {
				List<Property> properties = new ArrayList<Property>();
				for (Iterator<Element> iterator = element.elementIterator(); iterator
						.hasNext();) {
					Element element1 = (Element) iterator.next();
					Property property = new Property();
					String name = element1.attribute("name").getValue();
					String refId = element1.attribute("refId").getValue();
					property.setName(name);
					property.setRefId(refId);
					properties.add(property);
					logger.debug("Property: " + name + ", " + refId);
				}
				bean.setProperties(properties);
			}
			beanMap.put(id, bean);
			logger.debug("loaded bean:" + id + "," + clazz);
		}
		return beanMap;
	}

}
